// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//


#include <pollux/common/process/trace_history.h>

#include <melon/system/thread_id.h>

#include <algorithm>

namespace kumo::pollux::process {
    namespace {
        auto registry = std::make_shared<ThreadLocalRegistry<TraceHistory> >();
    }

    namespace detail {
        thread_local ThreadLocalRegistry<TraceHistory>::Reference traceHistory(
            registry);
    }

    TraceHistory::TraceHistory()
        : threadId_(std::this_thread::get_id()), osTid_(melon::getOSThreadID()) {
    }

    std::vector<TraceHistory::EntriesWithThreadInfo> TraceHistory::listAll() {
        std::vector<EntriesWithThreadInfo> results;
        registry->forAllValues([&](auto &history) {
            EntriesWithThreadInfo result;
            result.threadId = history.threadId_;
            result.osTid = history.osTid_;
            for (int i = 0; i < kCapacity; ++i) {
                const int j = (history.index_ + kCapacity - 1 - i) % kCapacity;
                if (!populated(history.data_[j])) {
                    break;
                }
                result.entries.push_back(history.data_[j]);
            }
            std::reverse(result.entries.begin(), result.entries.end());
            results.push_back(std::move(result));
        });
        return results;
    }
} // namespace kumo::pollux::process
